package com.by.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

@Component
public class RabbitUtils {

    @Autowired
    RabbitTemplate rabbitTemplate;


    ConcurrentNavigableMap<String,String> orderMap = new ConcurrentSkipListMap<>();


    /**
     * bean实例化后调用的初始化方法 只调用一次
     */
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if(null == correlationData) return;
            if(ack){
                //发布成功 从内存中移除
                orderMap.remove(correlationData.getId());
                System.out.println("消息【"+orderMap.get(correlationData.getId())+"】发送成功");
            }else {
                //发送失败 方案: 1.重新发送 2.记录日志
                System.out.println("消息【"+orderMap.get(correlationData.getId())+"】发送失败");
            }
        });
    }

    /**
     * 发送消息 用于生成订单
     * @param msg 消息
     */
    public void sendOrderMsg(String msg){
        //1.将发送的消息记录到redis中
        //2.发布确认
        String id = UUID.randomUUID().toString();
        orderMap.put(id,msg);//将消息和id关联
        rabbitTemplate.send(Constant.ORDER_EXCHANGE,Constant.ORDER_ROUTING_KEY,new Message(msg.getBytes()),new CorrelationData(id));

    }

    /**
     * 延迟发送消息
     * @param msg 要延迟发送的消息
     * @param lazyTime 延时时长 单位ms
     */
    public void sendLazyMsg(String msg,long lazyTime){
        MessageProperties properties = new MessageProperties();
        properties.setHeader("x-delay",lazyTime);
        rabbitTemplate.send(Constant.LAZY_EXCHANGE,Constant.LAZY_ROUTING_KEY,new Message(msg.getBytes(),properties));
    }
}
